package com.ncut.common;

import java.awt.Dimension;
import java.awt.Font;

import javax.swing.JPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;

public class Histogram2 extends ApplicationFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public Histogram2(String title) {
		super(title);
		JPanel jpanel = createDemoPanel();
		jpanel.setPreferredSize(new Dimension(500, 270));
		setContentPane(jpanel);
	}

	public static JPanel createDemoPanel() {
		JFreeChart jfreechart = createChart(createDataset());
		return new ChartPanel(jfreechart);
	}

	private static CategoryDataset createDataset() {

		double[][] data = new double[][] { { 672, 766, 223, 540, 126 },
				{ 325, 521, 210, 340, 106 }, { 332, 256, 523,240, 526 } };
		String[] rowKeys = { "苹果", "梨子", "葡萄" };
		String[] columnKeys = { "北京", "上海", "广州", "成都", "深圳" };
		CategoryDataset dataset = DatasetUtilities.createCategoryDataset(
				rowKeys, columnKeys, data);
		return dataset;
	}

	private static JFreeChart createChart(CategoryDataset categorydataset) {

		JFreeChart jfreechart = ChartFactory.createBarChart("水果销量图统计", "水果",
				"销量", categorydataset, PlotOrientation.VERTICAL, true, true,
				false);

		/**
		 * 解决中英文字体乱码 title(标题) legend(图释) plot(图表主体)。
		 */
		Font font = new Font("SimSun", 10, 20);

		jfreechart.getTitle().setFont(font);

		CategoryPlot plot = (CategoryPlot) jfreechart.getPlot();

		CategoryAxis domainAxis = plot.getDomainAxis();
		domainAxis.setTickLabelFont(font);// 设置X轴坐标上的字体
		domainAxis.setLabelFont(font);// 设置X轴上的标题的字体

		ValueAxis valueAxis = plot.getRangeAxis();// (柱状图的y轴)
		valueAxis.setTickLabelFont(font);// 设置y轴坐标上的字体
		valueAxis.setLabelFont(font);// 设置y轴上标题的字体

		jfreechart.getLegend().setItemFont(font);
		return jfreechart;
	}
	public static void main(String args[]) {
		Histogram2 barchartdemo1= new Histogram2("Bar Chart Demo");
		barchartdemo1.pack();
		RefineryUtilities.centerFrameOnScreen(barchartdemo1);
		barchartdemo1.setVisible(true);
	}
}
